/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/modules/holiday/index
/*  author : arida
/*  date   : 2017-6-4 18:24:50
/*  last   : 2017-9-6 18:16:24
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { List, Button } from "@ali/ding-ui";
import autobind from "autobind-decorator";

import { set, get } from "../../utils/db";

import {
  toUploadNewestVersion,
  openLink,
  confirm,
  setTitle,
  compareVersion,
  openConversation,
  chooseCustomContact,
  getCurrentUser,
  alert
} from "../../utils/dingtalk";

// actions
import {
  fetchHoliday,
  fetchAdminList,
  fetchEncodeUid
} from "../../actions/holiday/index.js";

// components
import Avatar from "../../components/Avatar";
import HolidayModal from "./modal";

import "./index.less";

const Item = List.Item;
// 将store注入组件的props
const mapStateToProps = state => ({ holiday: state.HOLIDAY_INFO });
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  // 区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      fetchHoliday,
      fetchAdminList,
      fetchEncodeUid
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Holiday extends Component {
  static defaultProps = {};
  // propTypes 验证
  static propTypes = {
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchHoliday: PropTypes.func.isRequired,
      fetchAdminList: PropTypes.func.isRequired,
      fetchEncodeUid: PropTypes.func.isRequired
    }).isRequired,
    holiday: PropTypes.shape({
      holidays: PropTypes.object,
      admins: PropTypes.array
    }).isRequired
  };
  constructor(props) {
    super(props);

    this.state = {
      modalVisible: false
    };

    setTitle({
      title: "出勤确认"
    });
  }
  componentWillMount() {
    this.props.actions.fetchHoliday();
    this.props.actions.fetchAdminList();
  }
  @autobind
  confirmByHand() {
    // 最理想的情况是userId+时间作为主键，而不是name+时间
    const info = this.props.holiday.holidays || {};
    set(`confirmByHand::${info.name}::${info.monthInfo}`, true);
    // re-render
    this.setState({});
  }
  @autobind
  contactUs() {
    this.setState({
      modalVisible: true
    });
  }
  @autobind
  hideModal() {
    this.setState({
      modalVisible: false
    });
  }
  @autobind
  sendMessage(admin) {
    const text = this.state.text; // 反馈信息
    const info = this.props.holiday.holidays || {};
    const nickName = info.name;
    const location = window.location;
    // 拼接url，用于分享链接
    const url =
      location.protocol +
      "//" +
      location.host +
      location.pathname +
      location.search +
      "&mode=preview" + // 通过链接进来的看不到底部按钮
      location.hash;

    if (!admin.emplId)
      return alert({title:"提示", message:"请选择管理员"});
    if (compareVersion("3.4.0", dd.version, true)) {
      // 大于等于3.4.0
      // 打开钉钉内部的聊天窗口
      const params = {
        title: `${nickName}${info.monthInfo}出勤统计`, // string, type为link时， 为分享标题
        content: `请点击查看我${info.monthInfo}出勤统计`, // string, type为link时， 为分享内容
        url,
        type: "1"
      };

      // 旧版本的接口，需要用到encodeUid，因此要从后端去换一下
      this.props.actions.fetchEncodeUid(admin.emplId).then(encUid => {
        openConversation({
          uid: encUid || "",
          title: params.title || "",
          content: params.content || "",
          image: params.image || "",
          url: params.url || "",
          type: params.type,
          onFail(err) {
            alert({ message: JSON.stringify(err) });
          }
        });
        if (text) {
          openConversation({
            uid: encUid || "",
            title: params.title || "",
            content: text || "",
            image: params.image || "",
            url: params.url || "",
            type: 0,
            onFail(err) {
              alert({ message: JSON.stringify(err) });
            }
          });
        }
      });
    } else {
      // 小于3.4.0 提醒升级
      confirm("请升级钉钉到最新版体验该功能", ["以后再说", "立即升级"], () => {
        if (result.buttonIndex === 1) {
          toUploadNewestVersion(url => openLink(url));
        }
      });
    }
  }

  /**
   * 
   * @param {时间} string   eg：2017-03-06
   * @ return {中文时间} string eg: 2017年03年06月 
   */
  formatDate(date) {
    if (!date) return;

    const ymd = date.split("-");
    const year = ymd[0];
    const month = ymd[1];
    const day = ymd[2];
    return `${year}年${month}月${day}日`;
  }
  @autobind
  selectAdmin() {
    const admins = this.props.holiday.admins;
    const corpId = this.props.holiday.holidays.corpId;

    (_this => {
      // dingding 的选人的组件
      chooseCustomContact({
        title: "选择管理员", //标题
        users: admins, //一组员工userid
        corpId: corpId, //加密的企业 ID，
        onSuccess: data => {
          // for display
          _this.setState({
            selectedAdmin: data[0]
          });
        }
      });
    })(this);
  }
  render() {
    const info = this.props.holiday.holidays || {};
    const currentAdmin = this.state.selectedAdmin || {};
    const isExceed = new Date() > new Date(info.closingDateTime);
    const useInfo = getCurrentUser();
    const avatar = useInfo && useInfo.avatar;
    const hideFooter = info.mode === "preview";
    // 过滤字段，得到全部于鏊展示的字段
    // 下面这个是用于自定义字段的。也就是说展示的内容完全由后台（url中的参数）定
    const items = Object.keys(info).filter(
      q =>
        [
          "hideFooter",
          "mode",
          "corpId",
          "name",
          "monthInfo",
          "closingDateTime",
          ""
        ].indexOf(q) === -1
    );
    // console.info("这些字段全是用于列表展示的", items);
    return (
      <div className="holiday">
        <div className="holiday-header">
          <div className="holiday-title">{info.monthInfo}出勤统计</div>
          <div className="holiday-desc">
            超过<span className="holiday_darken">
              {this.formatDate(info.closingDateTime)}
            </span>，未确认的出勤统计会自动确认
          </div>
          {// 超过时间 或者 手工确认要显示badge
          (isExceed ||
            get(`confirmByHand::${info.name}::${info.monthInfo}`)) && (
            <div
              className={`holiday-${get("feedback")
                ? "feedback"
                : "confirm"}-badge`}
            />
          )}
        </div>
        <List>
          <Item extra={info.monthInfo + " 出勤"}>
            <Avatar
              className="am-list-thumb-replace"
              avatar={avatar || ""}
              name={info.name || ""}
              size={"1rem"}
              font={"0.4rem"}
            />

            <span>{info.name}</span>
          </Item>
        </List>
        <br />

        <List className="holiday-list">
          {items.map(item => (
            <Item key={item} extra={info[item]}>
              {item}
            </Item>
          ))}
        </List>
        <HolidayModal
          visible={this.state.modalVisible}
          text={this.state.text}
          onTxtChange={text => this.setState({ text })}
          currentAdmin={currentAdmin}
          hideModal={this.hideModal}
          sendMessage={this.sendMessage}
          selectAdmin={this.selectAdmin}
        />
        <div className="holiday-footer">
          {!hideFooter && [
            <Button inline key="contact" onClick={this.contactUs}>
              联系管理员
            </Button>,
            <Button
              key="confirmByHand"
              disabled={
                get(`confirmByHand::${info.name}::${info.monthInfo}`) ||
                isExceed
              }
              type="primary"
              inline
              onClick={this.confirmByHand}
            >
              {get(`confirmByHand::${info.name}::${info.monthInfo}`) ? (
                "已确认"
              ) : isExceed ? (
                "已自动确认"
              ) : (
                "确认"
              )}
            </Button>
          ]}
        </div>
      </div>
    );
  }
}
